<?php
if(!defined('IN_BSTO')){ die('[ERROR] You cannot load this page directly !!!'); }

Class DB{
	private $registry;

	private $userManager    = null;
	private $bookManager    = null;
	private $staticManager  = null;
	private $catManager     = null;
	private $configManager 	= null;
	private $connection;

	function __construct(){
	   $argv = func_get_args();
        switch( func_num_args() )
        {
            default:
                case 0:
                self::__construct1();
            break;
                case 1:
                self::__construct1();
                self::__construct2($argv[0]);
            break;
        }

	}
    
    function __construct1(){
        $this->userManager      = new UserManager($this);
		$this->bookManager      = new BookManager($this);
		$this->staticManager    = new StaticManager($this);
		$this->catManager       = new CatManager($this);
		$this->configManager	= new ConfigManager($this);
    }
    
    function __construct2($registry){
        $this->registry = $registry;
	}
	/**
	 * get a (user, book, static, cat) Manager
	 */
	public function get($varName)
	{
		return $this->$varName;
	}

	/**
	 * load connection config from config.class.php
	 */
	public function getConnectionConfig()
	{
		//$cfg = new ConfigManager($this);

		//return $cfg;
	}
 
    private function printDBError($string)
    {
        if(isset($this->registry) && $this->registry->debug){
            die($string);
        }
        else {
            die('[DB Error] There are some errors with the database ! Plz contact the <a href="ymsgr:sendim?hung.vjnh">administrator</a> to fix it !');
        }
    }
 
	/**
	 * start connection
	 */
	public function startConnection()
	{
		$cfg = $this->configManager;

		$this->connection = mysql_connect($cfg->host, $cfg->username, $cfg->pwd);

		if(!$this->connection ){
			//$this->connection = mysql_connect("localhost","root","");
			if (!($this->connection)) {
				//echo "disconnect";
				$this->printDBError('Could not connect: ' . mysql_error());
			}
		}

		$selected = mysql_select_db($cfg->dbName, $this->connection);

		if(!$selected){
			//$selected = mysql_select_db("book store", $this->connection);
			if (!($selected)) {
				//echo "not selected";
				$this->printDBError('Could not select: ' . mysql_error());
			}
		}

		//return $this->connection;
	}

	/**
	 * close connection
	 */
	public function closeConnection()
	{
		if($this->connection){
			//mysql_close($this->connection);
			return true;
		}
		else {
			return false;
		}
	}

	/**
	 * Query function
	 * 
	 * Used to call from entity model classes
	 * 
	 * @param $query
	 */
	public function dbQuery($query)
	{
		if($this->connection){
			//$clearQuery = mysql_real_escape_string(trim($query), $this->connection);
			$handle =  mysql_query($query);
            if (!$handle) {
                $this->printDBError('Invalid query: ' . mysql_error().' '.$query);
                return false;
            }
            else {
                return $handle;
            }

		}
		else {
			return false;
		}

	}

	/**
	 * get Instances
	 * 
	 * @param $dataType
	 */
	public function getClassName($dataType)
	{
		if($dataType == 'user'){
			return new User($this);
		}
		else if($dataType == 'static'){
			return new StaticEntity();
		}
		else if($dataType == 'book'){
			return new Book($this);
		}
		else if($dataType == 'cat'){
			return new Category();
		}
		else if($dataType == 'config'){
			return new Config($this);
		}
		else if ($dataType == 'category') {
			return new Category();
		}
        else if ($dataType == 'plugin') {
			return new Plugin();
		}
		else return null;
	}


	/**
	 * query function
	 * 
	 * @author      hungvinh
	 * 
	 * @param SQL_Query $query
	 * @param string 	$datatype
	 */
	public function get_data($query, $datatype){
		if(!$this->connection){
			return false;
		}

		$queryResult = $this->dbQuery($query); //get resources from db

		$objectArray = array(); //array of object for each result row


		if ($queryResult)
		{
			while ($row = mysql_fetch_assoc($queryResult))
			{
				$object = $this->getClassName($datatype);
				 
				//set object atrribute
				foreach ($row as $key => $value)
				{
					$object->set($key, $value);
				}
				array_push($objectArray, $object);
			}
		}
		else {
			return null;
		}
		return $objectArray;
	}
    
    /**
     * get Data and parse it to a array
     * 
     * @author hungvjnh
     * 
     */
    public function getArrayData($query)
    {
		if(!$this->connection){
			return false;
		}
        
		$queryResult = $this->dbQuery($query); //get resources from db
        
        $objectArray = array(); //array of object for each result row
        
        if($queryResult){
            while($row = mysql_fetch_assoc($queryResult))
            {
                array_push($objectArray, $row);
            }
        }
        else {
            return null;
        }
        return $objectArray;
    }

	/**
	 * Used to get Book, Static objects(join 2 tables).
	 *
	 * @author	   aique
	 * @param 	   $query
	 * @return     array of array
	 */
	public function getMixedData($query)
	{
		$queryResult = $this->dbQuery($query); //get resources from db
		 
		$objectArrays = array(); //array of object for each result row

		if ($queryResult)
		{
			while ($row = mysql_fetch_assoc($queryResult))
			{
				$objectArray = array();
				 
				//set object atrribute
				foreach ($row as $key => $value)
				{
					$objectArray[$key] = $value;
				}
				array_push($objectArrays, $objectArray);

			}
		}
		return $objectArrays;
	}

	/**
	 * get accessable attributte of a table
	 * 
	 * @author hungvinh
	 * 
	 * @param string $table
	 */
	private function checkAccessableAttr($table){
		 //user -> username | email | phone | company | address | type
		 if($table == 'user'){
		 	return array('username', 'email', 'phone', 'company', 'address', 'type');
		 }
		 else if($table == 'book'){//book -> summary | detail | title
		 	return array('summary', 'detail', 'title');
		 }
		 else if($table == 'static'){//static -> detail | title
		 	return array('detail', 'title');
		 }
		 else if($table == 'category'){//// category -> name
		 	return array('name');
		 }
		 else if($table == 'config'){//// config -> key
		 	return array('key');
		 }
	}
	
	/**
	 * search data from database
	 *
	 * @author     hungvinh
	 *
	 * @param      $dataType
	 * @param      $attr
	 * @param      $value
	 */
	public function searchData($dataType, $attr, $value)
	{
		// check accessable attribute
		if(!in_array($attr, $this->checkAccessableAttr($dataType))){
			return null;
		}
		
		// get current user
		$user = $this->userManager->getCurrentUser();
		
		if(($user == null || $user->get('type') == "Normal") && $dataType != 'book'){
			return null;
		}
		
		// sql injection
		$dataType = mysql_real_escape_string($dataType);
		$attr	  = mysql_real_escape_string($attr);
		$value	  = mysql_real_escape_string($value);
		
		if($dataType == 'book' || $dataType == 'static')
		{
			// normal user only can access their book
			if($user->get('type') == "Normal"){
				$otherOption = 'AND e.uid = ' . $user->get('uid');
			}
			else {
				$otherOption = '';
			}
			// join 2 tables
			$query = "SELECT *
    					FROM " . $dataType . " AS s, entity AS e
    					WHERE s.nid = e.nid 
    						AND e.status = 1
    						AND " . $attr . " LIKE '%". $value . "%'" . $otherOption ;
			//echo $query;
			$result = $this->get_data($query, $dataType);
		}
		else {
			if($dataType == "category"){
				$otherOption = ' AND status = 1';
			}
			$query = "SELECT *
						FROM " . ($dataType == 'config'? 'configuration' : $dataType) . " 
						WHERE `" . $attr . "` LIKE '%". $value . "%'".$otherOption;
			
			//echo $query;
			$result =  $this->get_data($query, $dataType);
			
		}
		if(count($result) == 0){
			return null;
		}
		else {
			return $result;
		}
	}
	/**
	 * @ hung.vjnh
     * 
     * clean vietnamese character...
	 * 
	 * @param unknown_type $fragment
	 */
	public function cleanEntities($fragment)
	{
		$translite_symbols = array ( 
'#(à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ)#', 
'#(è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ)#', 
'#(ì|í|ị|ỉ|ĩ)#', 
'#(ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ)#', 
'#(ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ)#', 
'#(ỳ|ý|ỵ|ỷ|ỹ)#', 
'#(đ)#', 
'#(À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ)#', 
'#(È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ)#', 
'#(Ì|Í|Ị|Ỉ|Ĩ)#', 
'#(Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ)#', 
'#(Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ)#', 
'#(Ỳ|Ý|Ỵ|Ỷ|Ỹ)#', 
'#(Đ)#', 
"/[^a-zA-Z0-9\-\_]/"
) ; 
$replace = array ( 
'a', 
'e', 
'i', 
'o', 
'u', 
'y', 
'd', 
'A', 
'E', 
'I', 
'O', 
'U', 
'Y', 
'D', 
'-'
) ; 
$fragment = preg_replace($translite_symbols, $replace, $fragment); 
$fragment = preg_replace('/(-)+/', '-', $fragment);

		return $fragment;
	}
    
}

?>